Problem
Write a function that add two numbers A and B. You should not use + or any arithmetic operators.
Example
Given a=1 and b=2 return 3
Challenge
Of course you can just return a + b to get accepted. But Can you challenge not do it like that?
Note
**位运算笔记
Bit Manipulation Notes:**
加法:
^异或运算:求和;
&与运算:进位。
减法:
将负数化为正:~i, +1,两步完成取反
做加法
乘法:
a * b: if (b & 1) ans += a //b的最后一位是1,则结果+a
每次循环后a << 1, b >> 1; //b始终判断最后一位,a进位累加(小学生算式做乘法)
除法:(不赘述,O(log n))
http://blog.csdn.net/ojshilu/article/details/11179911
Solution
class Solution {
public int aplusb(int a, int b) {
// write your code here, try to do it without arithmetic operators.
if (b == 0) return a;
int sum = a^b;
int carry = (a&b) << 1;
return aplusb(sum, carry);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。